package task;

import com.opencsv.CSVWriter;
import org.apache.http.client.utils.DateUtils;
import org.gitlab4j.api.GitLabApi;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.Project;
import org.springframework.util.StringUtils;

import java.io.FileWriter;
import java.util.*;

/**
 * TODO
 *
 * @author ouyf
 * @date 11/18/2025 10:43
 * <p>
 */
public class Gitlab4jDemo {

    public static void main(String[] args) throws Exception{
        // Create a GitLabApi instance to communicate with your GitLab server
        GitLabApi gitLabApi = new GitLabApi("https://gitlab.com",
                "CSC-glpat-SKa52yzJQ8hUvSY13VDzcG86MQp1OjI4cTQK.01.100j999f6");
        gitLabApi.setDefaultPerPage(100);

// Get the list of projects your account has access to
        List<Project> projects = gitLabApi.getProjectApi().getMemberProjects();
        List<Map<String, String>> csvMaps = new ArrayList<>();
        for(Project project : projects){
            if(StringUtils.startsWithIgnoreCase(project.getNamespace().getFullPath(), "tbds/general")){
                HashMap<String, String> csvMap = new HashMap<>();
                Commit commit = gitLabApi.getRepositoryApi().getBranch(project.getId(), "main").getCommit();
                csvMap.put("projectName", project.getName());
                csvMap.put("namespace", project.getNamespace().getFullPath());
                csvMap.put("owner", commit.getAuthorEmail());
                csvMap.put("defaultBranch", project.getDefaultBranch());
                csvMap.put("gitHash", commit.getId());
                csvMap.put("lastCommitDate", DateUtils.formatDate(commit.getCommittedDate(), "yyyy-MM-dd HH:mm:ss"));
                csvMaps.add(csvMap);
                Thread.sleep(1000);
            }
        }
        CSVWriter csvWriter = new CSVWriter(new FileWriter("C:/data/tbds/gitlab-projects" +
                DateUtils.formatDate(new Date(), "yyyyMMddHHmmss") + ".csv"));
        for (Map<String, String> map : csvMaps) {
            String[] csvData = map.values().toArray(new String[0]);
            csvWriter.writeNext(csvData);
        }
        csvWriter.flush();
        csvWriter.close();
    }
}
